package cjm.task5.controller;


import cjm.task5.pojo.Record;
import cjm.task5.pojo.User;
import cjm.task5.service.RecordService;
import cjm.task5.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;

    // 跳转到login 页面
    @RequestMapping(value = "/login")
    public String login() {
        return "login";
    }

    // 登录的功能
    @RequestMapping(value = "/doLogin")
    public String checkLogin(
                            //String userid, String userPassword,
                             @RequestParam(value = "userid") String userid,
                             @RequestParam(value = "userPassword") String userPassword,
                             HttpSession session, Model model) {

        //System.out.println("/doLogin：" + userid + userPassword);
        userPassword = "{noop}" + userPassword;
        User user = this.userService.login(userid, userPassword);
        if (user==null) {
            // 表示用户不存在或密码错误
            //a.给出错误提示
            model.addAttribute("errorMsg", "账号、密码错误");
            //b.再次回到login
            return "/login";

        } else {
            // 该用户一定存在
            // 存session
            session.setAttribute("user", user);
            if(user.getIslock()==1){
                // 表示用户没有登录权限
                //a.给出错误提示
                model.addAttribute("errorMsg", "您当前没有登录权限");
                //b.再次回到login
                return "login";
            }
            else {
                if(user.getAdmin()==1){
                    List<Record> records = recordService.findRecordAll();
                    model.addAttribute("records",records);
                    return "redirect:/recordcon/searchAllRecord";
                }
                else {
                    String uri = "redirect:/yqfk/" + userid;
                    return uri;
                }

            }
        }

    }

    //退出登录
    @RequestMapping(value = "/outLogin")
    public String outLogin(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

    //跳转到获取密码页面
    @RequestMapping(value = "/goGetPassword")
    public String goGetPassword() {
        return "getPassword";
    }

    //忘记密码
    @RequestMapping(value = "/getPassword")
    public String getPassword(String userid, String username, HttpSession session, Model model) {
        String password = this.userService.getPassword(userid, username);
        if (password != null) {

            // 给出密码
            model.addAttribute("password1", password);
        } else {
            // 表示用户不存在或账号错误
            //a.给出错误提示
            model.addAttribute("errorMsg", "账号或用户名错误");
            //b.再次回到getPassword
        }
        return "getPassword";
    }

    //前往打卡页面
    @RequestMapping(value = "/yqfk/{userid}")
    public String yqfk(@PathVariable("userid") String userid,
                       Model model, HttpSession session) throws ParseException {

        String olduserid = (String) session.getAttribute("userid");
        //System.out.println("userid" + userid);
        //System.out.println("olduserid" + olduserid);
        if(!userid.equals(olduserid)){
            if(olduserid!=null)
                return "redirect:/login";
        }
        session.setAttribute("userid",userid);

        User user = userService.findUserByUserid(userid);

        Record record = new Record();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String d = sdf.format(date);
        record.setDate(d);//填报日期
        record.setName(user.getUsername());//姓名
        record.setUid(user.getId());

        //今天是否打卡 1-打卡了 0-未打卡
        Integer flag = recordService.todaySubmit(user.getId());
        model.addAttribute("flag",flag);

        List<String> str = recordService.getAllDateByUid(user.getId());
        if(str.size()>0){
            Record r = recordService.getRecordByDateAndUid(str.get(0),user.getId());
            record.setPhone(r.getPhone());
            record.setNamefriend(r.getNamefriend());
            record.setPhonefriend(r.getPhonefriend());
            record.setBody(r.getBody());
            record.setHospital(r.getHospital());
            record.setSchool(r.getSchool());
            record.setAddress(r.getAddress());
            record.setTemperature(r.getTemperature());
        }

        String msg;
        if(flag == 1){
            int num = 1;
            if (str.size()>1) {
                Date date1 = new Date();
                Date date2 = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                //System.out.println(str);
                //System.out.println("数组大小: " + str.size());
                for (int i = 0; i < str.size() - 1; i++) {
                    date1 = format.parse(str.get(i));
                    //System.out.println("date1:" + date1);
                    date2 = format.parse(str.get(i + 1));
                    //System.out.println("date2:" + date2);
                    int a = (int) ((date1.getTime() - date2.getTime()) / (1000 * 3600 * 24));
                    //System.out.println("i=" + i + "，相差" + a + "天");
                    if (a == 1) num++;
                    else break;
                }
            }
            //System.out.println("连续天数： " + num);
            msg = "您已连续打卡" +num+ "天！";

            record = recordService.getRecordByDateAndUid(d,user.getId());
            //System.out.println(record);
        }
        else {
            msg = "您今天未打卡！";
        }

        model.addAttribute("msg",msg);

        //System.out.println("yqfk函数："+record);
        model.addAttribute("record",record);
        return "yqfk";
    }

    //添加记录
    @PostMapping(value = "/addRecord")
    public String addRecord(Record record){
        //System.out.println("addRecord函数："+record);
        recordService.addRecord(record);
        User user = userService.findById(record.getUid());
        String uri = "redirect:/yqfk/" + user.getUserid();
        return uri;
    }
}
